// components/password/index.js
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    data: {
      type: Array,
      value: ['', '', '', '', '', '']
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    password: []
  },

  lifetimes: {
    attached() {
      const { data } = this.data;
      this.setData({
        password: data.map((item, index) => {
          if (index === 0) {
            return {
              value: item,
              focus: true
            };
          }
          return {
            value: item,
            focus: false
          };
        })
      });
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    handleToInput(event) {
      const { password = [] } = this.data;
      const { value } = event.detail;
      const { index } = event.currentTarget.dataset;
      if (value.length > 0) {
        if ((index + 1) > password.length) return false; // 输入完成
        this.setData({
          password: password.map((val, key) => {
            if (key === index) {
              return Object.assign({}, val, {
                value,
                focus: false
              });
            } else if (key === index + 1) {
              return Object.assign({}, val, {
                focus: true
              });
            }
            return Object.assign({}, val, {
              focus: false
            });
          })
        });
      } else {
        if (index == 0) return false; // 删除所有
        this.setData({
          password: password.map((val, key) => {
            if (key === index) {
              return Object.assign({}, val, {
                value,
                focus: false
              });
            } else if (key === index - 1) {
              return Object.assign({}, val, {
                focus: true
              });
            }
            return Object.assign({}, val, {
              focus: false
            });
          })
        });
      }
    },
  }
})